package cn.com.nes.site.module.service.monitor;


import cn.com.nes.common.em.platform.OpeMethodEnum;
import cn.com.nes.common.util.HttpUtils;
import cn.com.nes.common.util.XzqhUtils;
import cn.com.nes.mybatis.agent.ope.entity.IsEquipmentInfo;
import cn.com.nes.mybatis.agent.ope.entity.IsWxsb;
import cn.com.nes.mybatis.agent.ope.mapper.EquipmentMapper;
import cn.com.nes.mybatis.agent.ope.mapper.IsWxsbMapper;
import cn.com.nes.mybatis.callcenter.mapper.TXzqhMapper;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.module.dao.monitor.DeviceDaoImpl;
import cn.com.nes.site.module.dao.monitor.EquipmentInfoDaoImpl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EquipmentInfoService {

    @Resource
    private EquipmentInfoDaoImpl equipmentInfoDao;

    @Resource
    private DeviceDaoImpl deviceDao;

    @Resource
    private EquipmentMapper equipmentMapper;

    @Autowired
    private DeviceDaoImpl impl;

    @Resource
    private TXzqhMapper tXzqhMapper;

    @Resource
    private IsWxsbMapper wxsbMapper;


    @Transactional(rollbackFor = Exception.class)
    public PageData bindEquipment(DataReq req) throws Exception  {

        String wxId = (String) req.getReqData().get("wxId");
        String sbId = (String) req.getReqData().get("sbId");
        String sjly = "agent";
        // 判断该DTU是否存在

        IsWxsb isWxsb = wxsbMapper.getDtu(wxId);
        if (ObjectUtil.isEmpty(isWxsb)) {
            throw new Exception("该传输设备号不存在, 请重新选择");
        }

//        wxId = equipmentInfoDao.getWxSbByWxsbId(wxId);
//        if (StrUtil.isEmpty(wxId)) {
//            throw new Exception("该传输设备号不存在, 请重新选择");
//        }

        //根据设备id查找设备信息
        IsEquipmentInfo equipmentInfo = equipmentMapper.getEquipmentInfoBySbId(sbId);
        if (ObjectUtil.isNotNull(equipmentInfo)) {
            // 判断该无线id是否已绑定
            String  temp_wxId = equipmentInfoDao.getWxIdByWxId(wxId);
            if (StrUtil.isNotBlank(temp_wxId)) {
                throw new Exception("该传输设备号已被绑定, 请重新选择");
            }
            //判断该设备是否为机组设备
            if (ObjectUtil.isNull(equipmentInfo.getIsMaster()))
            {
                //单机设备只为当前设备绑定DTU
                equipmentInfo.setWxId(wxId);
                if (StrUtil.isNotEmpty(wxId)) {
                    equipmentInfo.setBdzt(1);
                }
                equipmentInfo.setXgsj(null);
                // modify by zhouy
                equipmentInfo.setProtocolId(isWxsb.getProtocolId());
                //更新无线设备的设备id
                Integer updateRes = equipmentMapper.updateTimeStampByWxId(wxId,sjly);
                if (updateRes != 1) {
                    throw new Exception("保存失败");
                }
                equipmentMapper.updateByPrimaryKeySelective(equipmentInfo);

            } else {
                //查询该设备所属机组下的所有设备
                List<IsEquipmentInfo> equipments = equipmentMapper.selectByExample(equipmentInfo.getSbPid());
                //添加机组PLC设备信息
                equipments.add(equipmentMapper.getEquipmentInfoBySbId(equipmentInfo.getSbPid()));
                //机组设备为所属机组下的所有设备绑定DTU
                for (IsEquipmentInfo equipment : equipments) {
                    equipment.setWxId(wxId);
                    // modify by zhouy
                    equipment.setProtocolId(isWxsb.getProtocolId());
                   // equipment.setSjly(sjly);
                    if (StrUtil.isNotEmpty(wxId)) {
                        equipment.setBdzt(1);
                    }
                    equipment.setXgsj(null);
                    Integer updateRes =  equipmentMapper.updateByPrimaryKeySelective(equipment);
                    if (updateRes != 1) {
                        //机组中任意一台设备绑定DTU失败,数据回滚
                        throw new Exception("绑定DTU失败");
                    }
                }
                //无线设备表更新设备id为PLC的id
                Integer updateRes = equipmentMapper.updateTimeStampByWxId(wxId,sjly);
                if (updateRes != 1) {
                    throw new Exception("保存失败");
                }
            }
        }else{
            return PageData.error("保存失败，查询不到设备");
        }

        return PageData.ok();
    }


    public PageData delEquipmentById(DataReq req) {

        String secret = (String) req.getReqData().get("secret");
        if (StrUtil.isBlank(secret)) {
            return PageData.error("解绑密码不能为空");
        }

        int code =  impl.verifyUntyingSecret(secret, req);
        if (code != 0) {
            return PageData.error("解绑密码不正确");
        }

        String relationId = equipmentInfoDao.getDeviceWorkOrder(req);
        if (StrUtil.isNotEmpty(relationId)) {
            //根据设备id,查找设备序列号
            String Sbxlh = equipmentInfoDao.getSbxlhBySbId(req);
            return PageData.error("设备序列号为:" + Sbxlh + "的设备,已生成安装工单,不可删除");
        }
        return deviceDao.delEquipmentById(req);
    }


    public PageData getCardInfo(DataReq req) {
        PageData res = new PageData();
        try {
            String iccid = equipmentInfoDao.getICCID(req);
            Map<String, Object> param = new HashMap<>(1);
            param.put("iccid", iccid);
            String url = OpeMethodEnum.getCardInfo.url();
            Map<String,String> headers = new HashMap<>();
            headers.put("key", req.getKey());
            String s = HttpUtils.sendPost(url, new JSONObject(param).toJSONString().getBytes(), headers);
            JSONObject result = JSONObject.parseObject(s);
            res.setRetCode(0);
            res.setRetMessage("OK");
            res.setDatas(result);

        } catch (Exception e) {
            res.setRetCode(9);
            res.setRetMessage("流量查询失败");
        }
        return res;
    }


    public PageData getWxList(DataReq req) {
        return equipmentInfoDao.getWxList(req);
    }

    /**
     * 得到设备信息（不脱敏）
     * @param req
     * @return
     */
    public PageData getEquipment(DataReq req) {
        return equipmentInfoDao.getEquipment(req);
    }

    @Transactional(rollbackFor = Exception.class)
    public PageData editInstallInfo(DataReq req) throws Exception {
        //equipmentInfoDao.updateZbqByDdid(req);
        return equipmentInfoDao.editInstallInfo(req);
    }

    public PageData setUntyingSecret(DataReq req) {
        String secret = (String) req.getReqData().get("secret");
        if (StrUtil.isBlank(secret)) {
            return PageData.error("解绑密码不能为空");
        }
        return equipmentInfoDao.setUntyingSecret(req);
    }

    public PageData  getSbCountByXzqh(DataReq req) {
        return equipmentInfoDao.getSbCountByXzqh(req);
    }

    public PageData  getSbCountByBrand(DataReq req) {
        return equipmentInfoDao.getSbCountByBrand(req);
    }

    public PageData  getSbCountBySjly(DataReq req) {
        return equipmentInfoDao.getSbCountBySjly(req);
    }
    public PageData  getSbCountByEquipmentType(DataReq req) {
        return equipmentInfoDao.getSbCountByEquipmentType(req);
    }

    public String getCxtjByDataRange(Byte dataRange, String xzqh, String userId, String departmentId,
                                     String manufactureId, String installTableAlias, String userTableAlias) {
        StringBuilder sb = new StringBuilder("");
        if (dataRange == null || dataRange == 2) {//默认按照区域查看
            if (xzqh.indexOf(",") > -1 && xzqh.indexOf("86") == -1) {
                String[] xzqhs = xzqh.split(",");
                if (xzqhs.length > 0) {//多个行政区划
                    sb.append(" and (");
                    for (int i = 0; i < xzqhs.length; i++) {
                        //根据行政区划,查找行政区划级别
                        String userXzqhJb = tXzqhMapper.getAreaCodeLevel(xzqhs[i]);
                        //根据行政区划级别,获取有效行政区划代码长度
                        String xzqhLength = XzqhUtils.subXzqhDigit(userXzqhJb);
                        //截取有效的行政区划
                        String xzqhUserEffective = xzqhs[i].substring(0, Integer.valueOf(xzqhLength));
                        if (i == 0) {
                            sb.append(installTableAlias).append(".xzqh like '").append(xzqhUserEffective).append("%' ");
                        } else {
                            sb.append(" or ")
                                    .append(installTableAlias)
                                    .append(".xzqh like '")
                                    .append(xzqhUserEffective)
                                    .append("%' ");
                        }
                    }
                    sb.append(") ");
                }
            } else if (StrUtil.isNotEmpty(xzqh) && xzqh.indexOf("86") == -1) {
                //根据行政区划,查找行政区划级别
                String userXzqhJb = tXzqhMapper.getAreaCodeLevel(xzqh);
                //根据行政区划级别,获取有效行政区划代码长度
                String xzqhLength = XzqhUtils.subXzqhDigit(userXzqhJb);
                //截取有效的行政区划
                String xzqhUserEffective = xzqh.substring(0, Integer.valueOf(xzqhLength));
                sb.append(" and ")
                        .append(installTableAlias)
                        .append(".xzqh like '")
                        .append(xzqhUserEffective)
                        .append("%' ");
            }
        } else if (dataRange == 1) {//按照部门上下级查看
            sb = new StringBuilder(" and ").append(userTableAlias)
                    .append(".department_id like '")
                    .append(departmentId)
                    .append("%' ");
        } else if (dataRange == 3) {//按照自己相关查看
            sb = new StringBuilder(" and (").append(userTableAlias)
                    .append(".user_id ='")
                    .append(userId)
                    .append("' or ")
                    .append(installTableAlias)
                    .append(".dd_id in(")
                    .append(" SELECT dd_id FROM is_work_order_info WHERE manufacture_id='")
                    .append(manufactureId)
                    .append("' AND (maintain_id='")
                    .append(userId)
                    .append("' or orderdirectorid='")
                    .append(userId)
                    .append("') AND sfsc=0 AND STATUS<6 ")
                    .append(")) ");
        }
        return sb.toString();
    }
}
